// 运行时配置
import { useIntl ,history,RunTimeLayoutConfig,RequestConfig,useParams,useModel} from '@umijs/max';
import services from '@/services/home';
import React, { useState,useRef } from 'react';
import { CaretDownOutlined,HomeOutlined,SearchOutlined,PlusCircleFilled,CaretLeftOutlined,SmileOutlined,
  DoubleRightOutlined ,SettingOutlined,BarcodeOutlined,NodeIndexOutlined,ToolOutlined,ContactsOutlined,
  PartitionOutlined,TeamOutlined,UserSwitchOutlined,TableOutlined} from '@ant-design/icons';
import { message,Space,Input } from 'antd';
import { flushSync } from 'react-dom';
import { Question, SelectLang, AvatarDropdown, AvatarName, BellOutlinedInfo,HeaderSystemSelect } from '@/components';
import { getGlobalApp,filterShowMenuData } from '@/utils/format';
const { getAuthInfo} =
  services.UserController;

const loginPath = '/login';
// import { loadMicroApp,prefetchApps } from 'qiankun';

const globalApp = getGlobalApp();
const _appRoutesList: any[] = [
  {
      key:'1',
      name: 'app1',
      path: '/app1',
      // hideInMenu: true,
      // component: './App1',
      // microApp: 'app1',
      // access: 'canReadPageApp1', // 权限定义返回值的某个 key
      // microAppProps: {
      //   autoSetLoading: true,
      // },
  },
  {
    key:'2',
    name: 'app2',
    path: '/app2',
    
    // hideInMenu: true,
    // access: 'canReadPageApp2', // 权限定义返回值的某个 key
    // exact: false,
    // component: () => import('@/components/SubAppContainer'),
    // component: './App2',
    // microApp: 'app2',
    // microAppProps: {
    //   autoSetLoading: true,
    // },
    routes: [
      {
        name: 'title2',
        // title: 'title2',
        // icon:<CaretDownOutlined />,
        path: '/app2',
        // access: 'canReadPageApp2_1', // 权限定义返回值的某个 key
        routes: [
          {
            name: 'title2_1',
            // title: 'title2',
            path: 'table',
            // access: 'canReadPageApp2_1', // 权限定义返回值的某个 key
          },
        ],
      },
      {
        name: 'title3',
        path: 'access',
      },
      
    ],
  },
  {
    key:'3',
    name: 'auth',
    path: '/auth',
    // hideInMenu: true,
    routes: [
      {
        path: "/",
      },
      {
        name: "account",
        path: "account"
      },
      {
        name: "position",
        path: "position"
      },
      {
        name: "role",
        path: "role"
      },
      {
        name: "empower",
        path: "empower"
      },
      {
        name: "menu",
        path: "menu"
      },
      
    ],
  },
  {
    key:'4',
    name: 'mes_system',
    path: '/mes_system',
    // hideInMenu: true,
    icon: 'dashboard',
    routes: [
      {
        path: "/",
      },
      {
        name: "workshopManagement",
        path: "workshopManagement"
      },
      {
        name: "productionlineManagement",
        path: "productionlineManagement"
      },
      {
        name: "teamManagement",
        path: "teamManagement"
      },
      {
        name: "shiftManagement",
        path: "shiftManagement"
      },
      {
        name: "barcodeManagement",
        path: "barcodeManagement",
        routes: [
          {
            name: "barcodeRules",
            path: "barcodeRules"
          },
          {
            name: "labelTemplate",
            path: "labelTemplate"
          },
          {
            name: "barcodePrinting",
            path: "barcodePrinting"
          },
        ]
      },
      {
        name: "materialData",
        path: "materialData"
      },
      {
        name: "bomData",
        path: "bomData"
      },
    
    ],
  }
];
// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{ 
  name: string,
  role: string,
  staticImg?: string,
  currentUser?: any,
  fetchUserInfo?: any,
  currentSystem?: any,
  extApps?: any,
  loading?: boolean,
  globalApp?:any,
  menuList?:any,
  appList?:any,
}> {
  // 如果不是登录页面，执行
  const { location } = history;

  const uniqueByKey=(arr:any, key:any)=>{
    const seen = new Set();
    return arr.filter((item:any) => {
      const keyValue = item[key];
      if (seen.has(keyValue)) {
        return false;
      } else {
        seen.add(keyValue);
        return true;
      }
    });
  }
  console.log('===getInitialState====',location);
  if (location.pathname != loginPath) {
   
    try {
      const _data:any = await getAuthInfo();
     
      if(_data.appCode == 'S0000'){
        const _flist =  globalApp.filter((_gl)=>{
          return _data.result?.menus.some((_si:any)=>_si.name == _gl.name);
        });
        let _applist =  _data.result?.apps.filter((_gl:any)=>{
          return globalApp.some((_si:any)=>_si.name == _gl.code);
        });
        console.log('===getAuthInfo====',_data,_applist);
        const new_applist = uniqueByKey(_applist, 'id');
        _applist=new_applist;
        // debugger
        return {
          name: 'Thinkcar', 
          // role: _data.result.length ? 'admin' :'',
          role: 'admin',
          staticImg: 'https://cop.thinkcar.cn/static/img/',
          // fetchUserInfo:_data.result,
          fetchUserInfo: _flist,
          currentUser: _data.result?.user || {},
          // menuList:_appRoutesList,
          menuList: _data.result?.menus || [],
          extApps: _data.result?.extApps || [],
          appList: new_applist || [],
          globalApp:globalApp
          //  settings: defaultSettings as Partial<LayoutSettings>,
        };
      }else{
        message.error(_data.appMesg || '失败，请重新登录');
        localStorage.clear();
        flushSync(()=>{
          history.replace('/login');
        });
      }
    } catch (error) {
      message.error('失败，请重试');
      localStorage.clear();
      flushSync(()=>{
        history.replace('/login');
      });
     
    }

   
    
  }
  
  return {
      name: 'Thinkcar', 
      role: 'admin',
      staticImg: 'https://cop.thinkcar.cn/static/img/',
      currentUser:{},
      // menuList:_appRoutesList,
      extApps:[],
      globalApp:globalApp,
      // fetchUserInfo: globalApp,
  };
}

// 获取微应用信息列表
// export const qiankun = getApps().then((data) => {
//   const apps = data?.DATA.filter((i: { entry: any }) => i.entry) || [];

//   const tmp = apps?.map((app: any) => {
//       return {
//           ...app,
//           // 增加一些子应用需要用到变量
//           props: {
//               globalState: {
//                   ...initState,
//               },
//           },
//       };
//   });
//   globalApp = tmp;
//   return {
//       apps: tmp,
//   };
// });

export const qiankun = {
   // 注册子应用信息
  apps: globalApp,
  lifeCycles: {
    // 所有子应用在挂载完成时，打印 props 信息
    async afterMount(props:any) {
      console.log('===afterMount====',props);
    },
  },
};
const IconMap = {
  smile: <SmileOutlined />,
  CaretLeftOutlined: <CaretLeftOutlined />,
  DoubleRightOutlined: <DoubleRightOutlined />,
  SettingOutlined: <SettingOutlined />,
  BarcodeOutlined: <BarcodeOutlined />,
  NodeIndexOutlined: <NodeIndexOutlined />,
  ToolOutlined: <ToolOutlined />,
  ContactsOutlined: <ContactsOutlined />,
  PartitionOutlined: <PartitionOutlined />,
  TeamOutlined: <TeamOutlined />,
  UserSwitchOutlined: <UserSwitchOutlined />,
  TableOutlined: <TableOutlined />
};


  
/**
 * 映射菜单对应的图标
 * */
const loopMenuItem = (menus: any[]): any[] =>
  menus.map(({ icon, routes, ...item }) => ({
    ...item,
    icon: icon && IconMap[icon as 'smile'],
    children: routes && loopMenuItem(routes),
  }));



const filterByMenuData = (
  data: any[],
  keyWord: string,
) => {
  const intl = useIntl();
  const _dlist = data
  .map((item) => {
    if (intl.formatMessage( { id: item.locale})?.includes(keyWord)) {
      return { ...item };
    }
    const children:any = filterByMenuData(item.children || [], keyWord);
    if (children.length > 0) {
      return { ...item, children };
    }
    return undefined;
  })
  .filter((item) => item) as any[];
  // debugger
  return _dlist;
};

export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }: any) => {
  const intl = useIntl();
  const _params = useParams();
  const [keyWord, setKeyWord] = useState('');
  const { currentAppMenu,currentTabList, updatedCurrentTabList,setCurrentSelectTab } = useModel('global');
  const refcTList = useRef<any>();
  const getCurrentTabList = () => {
    return currentTabList;
};

refcTList.current = getCurrentTabList;
  let _isShowMenu = ['/','/login','/home'].includes(history.location.pathname);
  history.location.pathname.indexOf('/tcpi/') != -1 && (_isShowMenu = true);
  let _fsystem:any = {};
    console.log('========layout==================',history.location.pathname,_isShowMenu,initialState?.fetchUserInfo,initialState?.menuList);
  if(!_isShowMenu && initialState?.fetchUserInfo){
    if(history.location.pathname.indexOf('/apphome') != -1){
      _params.id && (_fsystem = initialState?.fetchUserInfo.find((_item:any) => _item.id == _params.id));
    }
    if(history.location.pathname.indexOf('/auth') != -1){
     _fsystem = initialState?.fetchUserInfo.find((_item:any) => _item.name == 'auth');
    }
    if(history.location.pathname.indexOf('/mes_system') != -1){
     _fsystem = initialState?.fetchUserInfo.find((_item:any) => _item.name == 'mes_system');
    }
    if(history.location.pathname.indexOf('/gpt_system') != -1){
     _fsystem = initialState?.fetchUserInfo.find((_item:any) => _item.name == 'gpt_system');
    }
   
    // setInitialState((s:any) => ({ ...s, currentSystem: _fsystem }));
  }
  // console.log('========layout==================',_fsystem,history.location,_params,currentAppMenu);
  const _pr:any = {
    title: intl.formatMessage( { id: 'site.title'}),
    // title: false,
    logo: `${initialState?.staticImg}cop/cop_1.png`,
    // logo: <HomeOutlined />,
     // 退出登陆
    // logout: () => {
    //   history.push('/login');
    // },
    actionsRender: () => [
    <BellOutlinedInfo key="boumber" />, 
    // <SelectLang key="SelectLang" />
  ],
    avatarProps: {
      src: initialState?.currentUser?.avatar || 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
      title: <AvatarName />,
      render: (_:any, avatarChildren:any) => {
        // console.log(avatarChildren,_,'====avatarChildren==');
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
        // return <AvatarDropdown menu>{avatarChildren}</AvatarDropdown>;
      },
    },
    onPageChange: ( _item:any,) => {
      const { location } = history;
      // console.log("--------------------onPageChange------------------",location,_fsystem,_item,initialState,currentTabList );
      const _newlist = refcTList.current() || [];
      // _item && _newlist.push(_item);
      if(_item && _fsystem &&  Object.keys(_fsystem).length > 0 ){
          // const _fcml =initialState.menuList.find((_ml:any)=>_ml.key == _fsystem.id);
          const _fcml = _item.pathname.replaceAll('/','.');
          const _ishome = _fsystem.name+'home' == _item.pathname.replaceAll('/','') ;
          // console.log('======', _item.pathname.replaceAll('/',''),_fsystem.name);
          const _info:any = {
            tab: intl.formatMessage({ id: `menu${_ishome ? '.home':_fcml}`}),
            name: `menu${_fcml}`,
            key: _item.key,
            value: _item.pathname,
            search: _item.search,
            closable: !_ishome,
          }
          if(_newlist.length){
            const _some = _newlist.some((_si:any)=>_si.value == _item.pathname);
            !_some && (_ishome ? _newlist.unshift(_info):_newlist.push(_info));
          }else{
            _newlist.push(_info);
          }
          setCurrentSelectTab(_info);
          updatedCurrentTabList(_newlist);
      }
      
      // 如果没有登录，重定向到 login
      // if (!initialState?.currentUser && location.pathname !== loginPath) {
      //   history.push(loginPath);
      // }
    },
    menuExtraRender:({ collapsed }:any) =>{
      return !collapsed && (
            <Space
              // style={{
              //   marginBlockStart: 16,
              // }}
              align="center"
            >
              <Input
                style={{
                  borderRadius: 4,
                  backgroundColor: 'rgba(0,0,0,0.03)',
                }}
                prefix={
                  <SearchOutlined
                    style={{
                      color: 'rgba(0, 0, 0, 0.15)',
                    }}
                  />
                }
                placeholder={intl.formatMessage( { id: 'component.globalHeader.search.menu'})}
                variant="borderless"
                onPressEnter={(e) => {
                  setKeyWord((e.target as HTMLInputElement).value);
                }}
              />
              {/* <SearchOutlined
                style={{
                  color: 'var(--ant-primary-color)',
                  fontSize: 24,
                }}
                onClick={(e) => {
                  setKeyWord((e.target as HTMLInputElement).value);
                }}
              /> */}
            </Space>
          )
    },
    postMenuData:(menus:any) =>{
      console.log('===postMenuData=====',menus);
      return filterByMenuData(menus || [], keyWord);
    },
    onMenuHeaderClick:()=>{
      // console.log('====onMenuHeaderClick====');
    },
   
    headerTitleRender: (logo:any, title:any, _:any) => {
      const defaultDom = (
        <a className='tc_header_htr_1' 
            onClick={()=>{
              history.push('/tcpi/index');
            }}
          >
          {logo}
          {title}
        </a>
      );
      // if (typeof window === 'undefined') return defaultDom;
      // if (document.body.clientWidth < 1400) {
      //   return defaultDom;
      // }
      // if (_.isMobile) return defaultDom;

         let _rt = (
        <>
          {defaultDom}
        </>
      );
      if(_fsystem && Object.keys(_fsystem).length > 0 ){
        console.log('==========',_fsystem);
        _rt = (
          <>
            {defaultDom}
            <span className='tc_header_s_2'></span>
            {/* <img alt="" src={`${initialState?.staticImg}cop/cop_3.png`} className='tc_header_s_2' /> */}
            <HeaderSystemSelect systeminfo={_fsystem} >{(
              <p className='tc_header_s_1'>
                <img alt="" src={`${initialState?.staticImg}cop/cop_2.png`} className='tc_header_s_1_1' />
                &nbsp;{_fsystem.systemname} &nbsp; <CaretDownOutlined /></p>
            )}</HeaderSystemSelect>
          </>
        );
      }
      console.log('=====_rt=====',_rt,_fsystem);
      return _rt;
    },

    // menuHeaderRender: (logo:any, title:any, _:any) => {
    //   const defaultDom = (
    //     <a>
    //       {logo}
    //       {title}
    //     </a>
    //   );
    //   // if (typeof window === 'undefined') return defaultDom;
    //   // if (document.body.clientWidth < 1400) {
    //   //   return defaultDom;
    //   // }
    //   // if (_.isMobile) return defaultDom;
      
    //   let _rt = (
    //     <>
    //       {defaultDom}
    //     </>
    //   );
    //   if(_fsystem && Object.keys(_fsystem).length > 0 ){
    //     _rt = (
    //       <>
    //         <HeaderSystemSelect systeminfo={_fsystem} >{(
    //           <p className='tc_header_s_1'> {_fsystem.systemname} <CaretDownOutlined /></p>
    //         )}</HeaderSystemSelect>
    //       </>
    //     );
    //   }
    //   console.log('=====_rt=====',_rt,_fsystem);
    //   return _rt;
    // },
    menu: {
      // locale: false,
      // params: {
      //   userId: initialState?.currentUser?.userid,//引起菜单请求的参数
      // },
      request: async (params:any, defaultMenuData:any) => {
        // const _menuData = await getProjectList({key:'2222'});
        // console.log('====menu--------------==',initialState.menuList);
        // _fsystem?.id && (_appRoutesList[parseInt(_fsystem.id) -1].hideInMenu = false);
        // return _appRoutesList;
        return loopMenuItem(initialState.menuList);
        // return loopMenuItem(data);
      },
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
        // initialState.currentUser 中包含了所有用户信息
        // routes[0].children.push(_ru);
    },
    layout: 'mix', // sidemenu   top   mix
    menuDataRender: ( menuData:any) => {
      // const dynamicMenuData = [...menuData]; // 复制原始菜单数据
      // // 假设有一个全局状态或者条件来决定是否隐藏 '/about' 菜单项
      // const shouldHideAbout = true; // 这里可以是任何条件，比如从全局状态中获取的值
      if(menuData[0] && menuData[0].path != '/'){
        // 遍历菜单项，根据条件动态地修改 hideInMenu
        menuData.forEach((_item:any) => {
            _item.hideInMenu = _item.name != _fsystem?.name; // 动态设置 hideInMenu 为 true : 隐藏自己和子菜单
            _item.flatMenu = _item.name == _fsystem?.name; // 动态设置 flatMenu 为 true : 子项往上提，仍旧展示,
            _item.children = filterShowMenuData(_item.children)
        });
        // _fsystem?.id && (menuData[parseInt(_fsystem.id) -1].hideInMenu = false);
        // console.log("--------------------menuDataRender2------------------", _isShowMenu,menuData,_fsystem );
      }
      

      return menuData;
      // 使用处理后的菜单数据进行渲染
      // return <Menu items={dynamicMenuData} />;
      // return _isShowMenu ? false : <MenuRender menuData={menuData} location={location} systeminfo={_fsystem} />;
    },
  };
  _isShowMenu && (_pr.menuRender = false);
  return _pr;
};

// export function onRouteChange({ routes,matchedRoutes,location, action }: any) {
//   console.log('===============onRouteChange== s==');
//   console.log(routes); //路由集合
//   console.log(matchedRoutes); //当前匹配的路由及其子路由
//   console.log(location); //location及其参数
//   console.log(action); //当前跳转执行的操作
//   console.log('===============onRouteChange==end==');
// }

export function useQiankunStateForSlave() {
  const [globalState, setGlobalState] = useState<any>({
    slogan: 'Hello MicroFrontend',
  });

    // 父应用提供unmountCache方法，子应用卸载时，将虚拟dom相关数据缓存到基座
    const unmountCache = (cacheKey:any, instance:any) =>{
      console.log('==unmountCache===',cacheKey,instance);
      if (!cacheKey || !instance) return;
      // // 缓存当前虚拟dom相关数据之前，判断当前页签中是否含有当前子应用的页签，不包含时，不缓存
      // if (!this.appRootMenuCodes.includes(cacheKey)) return;
  
      // const cachedInstance = {};
      // cachedInstance._vnode = instance._vnode;
      // // keepalive设置为必须 防止进入时再次created，同keep-alive实现
      // if (!cachedInstance._vnode.data.keepAlive)
      //   cachedInstance._vnode.data.keepAlive = true;
      // cachedInstance.$router = instance.$router;
      // cachedInstance.apps = [].concat([instance.$router.apps[0]]);
      // cachedInstance.$router.app = null;
      // this.microAppCacheMap.set(cacheKey, cachedInstance);
    };


  return {
    globalState,
    setGlobalState,
    unmountCache
  };
}


// 请求拦截
export const request: RequestConfig = {
  // timeout: 1000,
  // other axios options you want
  errorConfig: {
    errorHandler(){
        console.log('===errorHandler=');
    },
    errorThrower(){
      console.log('===errorThrower=');
    }
  },
  requestInterceptors: [
    // 直接写一个 function，作为拦截器
    (url, options) =>
      {
        console.log('===requestInterceptors=',url, options);
        localStorage.getItem('tc_all_token') &&  (options.headers!.token = localStorage.getItem('tc_all_token') || "");
        // do something
        return { url, options }
      },
    // 一个二元组，第一个元素是 request 拦截器，第二个元素是错误处理
    [(url, options) => {
      // console.log('===requestInterceptors2=',url, options);
      return { url, options }
    }, (error) => {return Promise.reject(error)}],
    // 数组，省略错误处理
    [(url, options) => {
      // console.log('===requestInterceptors3=',url, options);
      return { url, options }
    }]
  ],
  responseInterceptors: [
     // 直接写一个 function，作为拦截器
     (response) =>
     {
       // 不再需要异步处理读取返回体内容，可直接在data中读出，部分字段可在 config 中找到
       const { data = {} as any, config } = response;
      //  console.log('===responseInterceptors1=',response,data,config);
       // do something
       return response
     },
   // 一个二元组，第一个元素是 request 拦截器，第二个元素是错误处理
   [(response) => {return response}, (error) => {return Promise.reject(error)}],
   // 数组，省略错误处理
   [(response) => {return response}]
  ]
};


// import { registerMicroApps } from 'qiankun';
// const apps = [
//   {
//     name: "tcpi", // 子应用的名称
//     // entry: '//localhost:3000', // 默认会加载这个路径下的html，解析里面的js
//     entry: 'http://test2.xhinkcar.cn/tcpi/', // 测试环境
//     activeRule: "/tcpi", // 匹配的路由
//     container: '#sub-app-tcpi',// 加载的容器
//   },
// ]

// // 2. 注册子应用
// registerMicroApps(apps, {
//   beforeLoad: [async app => console.log('before load', app.name)],
//   beforeMount: [async app => console.log('before mount', app.name)],
//   afterMount: [async app => console.log('after mount', app.name)],
// })